package org.linlinjava.litemall.admin.shiro;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.linlinjava.litemall.core.exception.enums.GlobalErrorCodeConstants;
import org.linlinjava.litemall.core.exception.util.ServiceExceptionUtil;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.domain.LitemallToken;
import org.linlinjava.litemall.db.service.LitemallAdminService;
import org.linlinjava.litemall.db.service.LitemallTokenService;
import org.linlinjava.litemall.db.util.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class TokenAuthenticationFilter extends AccessControlFilter {
    @Autowired
    private LitemallTokenService litemallTokenService;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        String token = WebUtils.toHttp(request).getHeader(AdminWebSessionManager.LOGIN_TOKEN_KEY);
        if (token == null) {
            return false;
        }
        this.litemallTokenService = (LitemallTokenService) SpringUtils.getBean("litemallTokenService");
        // 在数据库中验证token
        LitemallToken loginToken = litemallTokenService.getOne(Wrappers.lambdaQuery(LitemallToken.class)
                .eq(LitemallToken::getToken, token));
        if(loginToken == null){
            throw ServiceExceptionUtil.exception(GlobalErrorCodeConstants.UNAUTHORIZED_ACCOUNT_LOGIN_ELSEWHERE);
            //return false;
        }
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginToken.getUsername(), loginToken.getPassword());
        currentUser.login(usernamePasswordToken); // 进行登录认证
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
}
